// import store from "storejs";
import storage from "./storage";
import { LOGIN_TOKEN, LOGIN_TEL } from "./Const";
let db;
let tableName = "login_data";

export async function initDatabase(DB) {
  db = DB;
  await db
    .executeSql(
      `
      CREATE TABLE IF NOT EXISTS ${tableName}(
        token VARCHAR(256),
        tel VARCHAR(55)
      );`
    )
    .then(ret => {
      db.transaction(tx => {
        tx.executeSql(`SELECT * FROM ${tableName};`, [], (tx, result) => {
          if (result.rows.length == 0) {
            db.executeSql(
              `INSERT INTO ${tableName} (token, tel) VALUES ('','');`
            )
              .then(([tx, results]) => {
                console.log("insert: " + JSON.stringify(tx));
              })
              .catch(ret => {
                "error:" + JSON.stringify(ret);
              });
          }
          // alert(JSON.stringify(result));
        });
      });
    })
    .catch(error => {
      console.log(error);
    });

  // loginSuccess('3ed51d37-9562-431b-b020-1689dc1c6b5a', '18705935317');
}

export function closeDatabase() {
  if (db) db.close();
}

export async function update(token = "", tel = "") {
  try {
    let [result] = await db.executeSql(
      `UPDATE ${tableName} SET token = '${token}', tel = ${tel};`
    );
    // alert(JSON.stringify(result));
  } catch (e) {
    // alert(JSON.stringify(e));
  }
}

export async function loginSuccess(token, tel) {
  if (token) storage.set(LOGIN_TOKEN, token);
  if (tel) storage.set(LOGIN_TEL, tel);
  return await update(token, tel);
}

export async function logOut() {
  storage.remove(LOGIN_TOKEN);
  storage.remove(LOGIN_TEL);
  await db.transaction(async tx => {
    await tx
      .executeSql(`UPDATE ${tableName} SET token = '', tel = '';`)
      .then(([tx, result]) => {
        // alert(JSON.stringify(result));
      });
  });
}

export async function getLoginState() {
  let token = storage.get(LOGIN_TOKEN);
  let [data] = await db.executeSql(`SELECT * FROM ${tableName};`);
  let userData = data.rows.item(0);
  if (userData.token) {
    storage.set(LOGIN_TOKEN, userData.token);
    storage.set(LOGIN_TEL, userData.tel);
  }

  return data.rows.item(0).token || token;
}

export function beforeLoginHandle(navigate) {
  if (!getLoginState()) navigate("Login");
}
